package com.xoms.front.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradeCancelResponse;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.xoms.front.cache.dao.PayCacheDao;
import com.xoms.front.constants.AppConfig;
import com.xoms.front.constants.StringConstants;
import com.xoms.front.controller.res.BaseResult;
import com.xoms.front.controller.res.ObjectResult;
import com.xoms.front.controller.res.bean.ROrderStatusBean;
import com.xoms.front.model.OrderBean;
import com.xoms.front.model.ProOrderBean;
import com.xoms.front.model.ProStockBean;
import com.xoms.front.persist.dao.OrderDao;
import com.xoms.front.persist.dao.ProOrderDao;
import com.xoms.front.persist.dao.ProStockDao;
import com.xoms.front.service.PayService;
import com.xoms.front.service.exception.ServiceException;
import com.xoms.front.util.pay.ali.AliPayConstants;
import com.xoms.front.util.pay.ali.AliPayManager;
import com.xoms.front.util.pay.ali.AlipayUtil;
import com.xoms.front.util.pay.wx.WXPayConstants;
import com.xoms.front.util.pay.wx.WXPayManager;
import com.xoms.front.util.pay.wx.callback.WXPayCallbackRequest;
import com.xoms.front.util.pay.wx.micropay.WXMicropayResponse;
import com.xoms.front.util.pay.wx.orderquery.WXOrderqueryResponse;
import com.xoms.front.util.pay.wx.unifiedorder.WXUnifiedOrderResponse;
import com.xoms.util.StringUtil;

@Service
public class PayServiceImpl implements PayService {
	private static final Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);

	@Autowired
	OrderDao orderImpl;

	@Autowired
	PayCacheDao payCacheImpl;

	@Autowired
	ProStockDao proStockImpl;

	@Autowired
	ProOrderDao proOrderImpl;

	public static void main(String[] args) {
		PayServiceImpl app = new PayServiceImpl();

		// AlipayManager.getInstance().tradeQuery("", "2018052521001004870250121509");

		// app.scanAuthCode2Store();

		// app.wxScanQrcode2Store("2018052521001004870250121511", "192.168.1.1");
		//
		// AlipayTradePayResponse alipayTradePayResponse = AliPayManager.getInstance()
		// .scanAuthCode2Store("20150320010101010", "280009920089552072", "烟酒",
		// "NJ_001", 0.01);
		// System.out.println(JSON.toJSONString(alipayTradePayResponse));
		//
		// //
		// {"body":"{\"alipay_trade_precreate_response\":{\"code\":\"10000\",\"msg\":\"Success\",\"out_trade_no\":\"20150320010101009\",\"qr_code\":\"https:\\/\\/qr.alipay.com\\/bax09002c8cqe8hnniei00e8\"},\"sign\":\"bhkCUbWxS4GbSSzLS793sw6HK4CwyqrWzLObCS9HImD3QxvcXvI1cR+I5gKmtx8I0PDTf8EjO9NU7z0DZE6BzJ4SCFg958XlllXdgWbP4p8bd6DeNjtfStTlstHO2pW4tSTIdYe6JLJW9MZe/TGmLLxmk7FofkPfgkUe/kTLnUS9TyWUfTFzy6crSpXB9jaAaqrWgWuD55eEkFYTZcICg1hFHD6gUNyztrVBqa70/+k/i7ikx93YP60w4ZSKRSnwEowYKCQB9orA+nQJYl5FbbZtMkZu5k6nQDfGi3xMsIBUSLLKJgQXrLx0xBmmL0M9EnWjejo03fbTuLx4ecxKEw==\"}","code":"10000","errorCode":"10000","msg":"Success","outTradeNo":"20150320010101009","params":{"biz_content":"{\"out_trade_no\":\"20150320010101009\",\"store_id\":\"NJ_001\",\"subject\":\"烟酒\",\"timeout_express\":\"90m\",\"total_amount\":\"0.01\"}"},"qrCode":"https://qr.alipay.com/bax09002c8cqe8hnniei00e8","success":true}
		// AlipayTradePrecreateResponse response =
		// AliPayManager.getInstance().scanQrcode2Store("20150320010101011", "烟酒",
		// "NJ_001", 0.01);
		// System.out.println(JSON.toJSONString(response));
		// String qr_code = response.getQrCode();
		// System.out.println(qr_code);

	}

	@Override
	public ObjectResult<String> wxScanQrcode(String outTradeNo, String spbill_create_ip) {
		ObjectResult<String> result = new ObjectResult<String>();
		// 查询订单信息
		OrderBean order = orderImpl.selectByOrderNo(outTradeNo);
		if (order == null) {
			throw new ServiceException("object_is_not_exist", "订单信息");
		}
		if (order.getGetMoney() == null) {
			result.setFlag(false);
			result.setMsg("订单金额为空");
			return result;
		}

		String device_info = "NJ_001"; // 设备号
		String body = order.getSubject() == null ? "" : order.getSubject(); // 订单标题
		String detail = order.getDetail() == null ? "" : order.getDetail(); // 商品详情
		String attach = ""; // 附加数据
		int totalAmount = (int) (order.getGetMoney() * 100); // 微信支付 金额单位 分
		String notify_url = AppConfig.instance().getWebAppPath() + StringConstants.getInstance().WECHAT_PAY_CALLBACK;
		String storeId = "NJ_001"; // 门店唯一标识 商户门店编号
		String storeName = "X影院"; // 门店名称
		String storeAreacode = "440305";
		String storeAddress = "北京市海淀区";

		// 预下单获取支付二维码内容
		WXUnifiedOrderResponse response = WXPayManager.getInstance().unifiedOrder(device_info, body, detail, attach,
				outTradeNo, totalAmount, spbill_create_ip, notify_url, storeId, storeName, storeAreacode, storeAddress);
		logger.debug("wxScanQrcode WXUnifiedOrderResponse ------>: " + JSON.toJSONString(response));

		if (response == null) {
			result.setFlag(false);
			return result;
		}
		// 状态码 FAIL
		if (WXPayConstants.FAIL.equals(response.getReturn_code())) {
			result.setFlag(false);
			result.setMsg(response.getReturn_msg());
			return result;
		}
		// 业务结果 FAIL
		if (WXPayConstants.FAIL.equals(response.getResult_code())) {
			result.setFlag(false);
			result.setMsg(response.getErr_code() + " " + response.getErr_code_des());
			return result;
		}

		// 支付类型
		if (!WXPayConstants.TRADE_TYPE_NATIVE.equals(response.getTrade_type())) {
			result.setFlag(false);
			result.setMsg("支付类型不正确！");
			return result;
		}

		// 二维码链接
		String code_url = response.getCode_url();
		result.setData(code_url);
		result.setFlag(true);
		return result;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public ObjectResult<String> wxScanAuthCode(String orderNo, String spbill_create_ip, String authCode) {
		ObjectResult<String> result = new ObjectResult<String>();
		// 查询订单信息
		OrderBean order = orderImpl.selectByOrderNo(orderNo);
		if (order == null) {
			throw new ServiceException("object_is_not_exist", "订单信息");
		}
		if (order.getGetMoney() == null) {
			result.setFlag(false);
			result.setMsg("订单金额为空");
			return result;
		}

		String device_info = "NJ_001"; // 设备号
		String body = order.getSubject() == null ? "" : order.getSubject(); // 订单标题
		String detail = order.getDetail() == null ? "" : order.getDetail(); // 商品详情
		String attach = ""; // 附加数据
		int totalAmount = (int) (order.getGetMoney() * 100); // 微信支付 金额单位 分
		String storeId = "NJ_001"; // 门店唯一标识 商户门店编号
		String storeName = "X影院"; // 门店名称
		String storeAreacode = "440305";
		String storeAddress = "北京市海淀区";

		WXMicropayResponse response = WXPayManager.getInstance().micropay(device_info, body, detail, attach, orderNo,
				totalAmount, spbill_create_ip, authCode, storeId, storeName, storeAreacode, storeAddress);

		logger.debug("wxScanAuthCode WXMicropayResponse ---->:\n" + JSON.toJSONString(response));
		if (response == null) {
			result.setFlag(false);
			return result;
		}

		// 状态码 FAIL
		if (WXPayConstants.FAIL.equals(response.getReturn_code())) {
			throw new ServiceException("pay_error", response.getReturn_msg());
		}

		// 业务结果 FAIL，只有在调用微信服务器并且支付成功之后，返回SUCCESS，如果不是，如：等待用户支付场景
		if (WXPayConstants.FAIL.equals(response.getResult_code())) {
			throw new ServiceException("pay_error", response.getErr_code() + " " + response.getErr_code_des());
		}

		// 微信支付订单号
		String transaction_id = response.getTransaction_id();

		// 更新订单状态
		updateOrderPaySuccess(order, transaction_id, 1, JSON.toJSONString(response));

		boolean flag = orderImpl.updateStatusByOid(order.getOid(), transaction_id, 1, null) > 0;
		if (!flag) {
			flag = orderImpl.updateStatusByOid(order.getOid(), transaction_id, 1, null) > 0;
		}
		result.setFlag(flag);
		return result;
	}

	/**
	 * 用户扫描商户商品购买的二维码
	 */
	@Override
	public ObjectResult<String> aliScanQrcode(String outTradeNo) {
		ObjectResult<String> result = new ObjectResult<String>();

		// 查询订单信息
		OrderBean order = orderImpl.selectByOrderNo(outTradeNo);
		if (order == null) {
			throw new ServiceException("object_is_not_exist", "订单信息");
		}
		if (order.getGetMoney() == null) {
			result.setFlag(false);
			result.setMsg("订单金额为空");
			return result;
		}

		String storeId = "NJ_001"; // 商户门店编号
		String subject = order.getSubject(); // 订单标题

		// 订单金额
		double totalAmount = AlipayUtil.getDouble(order.getGetMoney());

		// 当面支付
		AlipayTradePrecreateResponse response = AliPayManager.getInstance().scanQrcode2Store(outTradeNo, subject,
				storeId, totalAmount,
				AppConfig.instance().getWebAppPath() + StringConstants.getInstance().ALIPAY_CALLBACK);
		logger.debug("aliScanQrcode response----->: " + JSON.toJSONString(response));
		/// {"alipay_trade_pay_response":{"code":"10000","msg":"Success","buyer_logon_id":"229***@qq.com","buyer_pay_amount":"0.01","buyer_user_id":"2088702526244871","fund_bill_list":[{"amount":"0.01","fund_channel":"PCREDIT"}],"gmt_payment":"2018-05-25
		/// 00:24:06","invoice_amount":"0.01","out_trade_no":"20150320010101006","point_amount":"0.00","receipt_amount":"0.01","total_amount":"0.01","trade_no":"2018052521001004870250121509"},"sign":"OYyxfzArLHIOCKdrCpPDCQOpPQ3zXcxNCXF2MbAZvIFQF0+W/QsWn0Ju0zlTMkvswlN1wxR7O5juOUVqL5GmEvFyHJ8/yCcp5X0NCkLcq5dVButiHhTecQWDz4vrx+xuIorxYEhpj1ZaNqNYPhoF8pY38x2Cl7600p8ZOSWKud2kQrBHecV9s5o8NpEL0SS88w/mK9vLM/+LZD91fVuumGtt0Yr7Q5NRHhZ75FppthPXeRrrqDMTnvNmld0KCxiueF7hzT5JmMHfGdxWgwPLHhWLtxHMXD0rSpMLr3umtaFW6kdC2fdH1YMt+qkH36ILRMmbSI3+AhTbhqla15BdCw=="}

		// 响应不能为空
		if (response == null) {
			result.setFlag(false);
			return result;
		}

		if ("10000".equals(response.getCode())) {
			// 接口调用成功，调用结果请参考具体的API文档所对应的业务返回参数
			result.setData(response.getQrCode());
			result.setFlag(true);
		} else if ("40001".compareTo(response.getCode()) <= 0 && "40006".compareTo(response.getCode()) >= 0) {
			// 业务处理失败 具体失败原因请参考“公共错误码”。其它请参考API文档。
			result.setFlag(false);
			result.setMsg(response.getSubCode() + " " + response.getSubMsg());
			return result;
		} else if ("20000".equals(response.getCode())) {
			// 业务出现未知错误或者系统异常 业务出现未知错误或者系统异常
			result.setFlag(false);
			result.setMsg(response.getMsg() + " 稍后重试！ \n" + response.getSubCode() + " " + response.getSubMsg());
			return result;
		}
		return result;
	}

	/**
	 * 当面付,商户扫描用户的支付宝二维码/条形码
	 * 
	 * @param outTradeNo
	 *            商户订单号，需要保证不重复
	 * @param authCode
	 *            用户付款码，25~30开头的长度为16~24位的数字，实际字符串长度以开发者获取的付款码长度为准
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public BaseResult aliScanAuthCode(String orderNo, String authCode) {
		BaseResult result = new BaseResult();
		boolean flag = false;
		// 查询订单信息
		OrderBean order = orderImpl.selectByOrderNo(orderNo);
		if (order == null) {
			throw new ServiceException("object_is_not_exist", "订单信息");
		}
		if (order.getGetMoney() == null) {
			result.setFlag(false);
			result.setMsg("订单金额为空");
			return result;
		}

		String storeId = "NJ_001"; // 商户门店编号
		String subject = "烟酒"; // 订单标题
		// 订单金额
		double totalAmount = AlipayUtil.getDouble(order.getGetMoney());

		// 当面支付
		AlipayTradePayResponse response = AliPayManager.getInstance().scanAuthCode2Store(orderNo, authCode, subject,
				storeId, totalAmount);
		logger.debug("aliScanAuthCode response----->: " + JSON.toJSONString(response));
		/// {"alipay_trade_pay_response":{"code":"10000","msg":"Success","buyer_logon_id":"229***@qq.com","buyer_pay_amount":"0.01","buyer_user_id":"2088702526244871","fund_bill_list":[{"amount":"0.01","fund_channel":"PCREDIT"}],"gmt_payment":"2018-05-25
		/// 00:24:06","invoice_amount":"0.01","out_trade_no":"20150320010101006","point_amount":"0.00","receipt_amount":"0.01","total_amount":"0.01","trade_no":"2018052521001004870250121509"},"sign":"OYyxfzArLHIOCKdrCpPDCQOpPQ3zXcxNCXF2MbAZvIFQF0+W/QsWn0Ju0zlTMkvswlN1wxR7O5juOUVqL5GmEvFyHJ8/yCcp5X0NCkLcq5dVButiHhTecQWDz4vrx+xuIorxYEhpj1ZaNqNYPhoF8pY38x2Cl7600p8ZOSWKud2kQrBHecV9s5o8NpEL0SS88w/mK9vLM/+LZD91fVuumGtt0Yr7Q5NRHhZ75FppthPXeRrrqDMTnvNmld0KCxiueF7hzT5JmMHfGdxWgwPLHhWLtxHMXD0rSpMLr3umtaFW6kdC2fdH1YMt+qkH36ILRMmbSI3+AhTbhqla15BdCw=="}

		if (response == null) {
			result.setFlag(false);
			result.setMsg("异常");
			return result;
		}

		if (!response.isSuccess()) {
			result.setFlag(false);
			result.setMsg("调用支付宝接口失败");
			return result;
		}

		// 支付宝28位交易号,数据库需要记录交易号
		String tradeNo = response.getTradeNo();
		if ("10000".equals(response.getCode())) {
			// 支付成功
			// 记录交易结果并在客户端显示支付成功，进入后续的业务处理。
			// 更新订单状态
			updateOrderPaySuccess(order, tradeNo, 1, JSON.toJSONString(response));
			result.setFlag(true);
			return result;
		} else if ("40004".equals(response.getCode())) {
			// 支付失败
			// 记录交易结果并在客户端显示错误信息（display_message)。
			result.setFlag(false);
			result.setMsg(response.getSubCode() + " " + response.getSubMsg());
			return result;
		} else if ("10003".equals(response.getCode())) {
			// 等待用户付款
			// 发起轮询流程：等待5秒后调用交易查询接口alipay.trade.query通过支付时传入的商户订单号(out_trade_no)查询支付结果（返回参数TRADE_STATUS），如果仍然返回等待用户付款（WAIT_BUYER_PAY），则再次等待5秒后继续查询，直到返回确切的支付结果（成功TRADE_SUCCESS
			// 或
			// 已撤销关闭TRADE_CLOSED），或是超出轮询时间。在最后一次查询仍然返回等待用户付款的情况下，必须立即调用交易撤销接口alipay.trade.cancel将这笔交易撤销，避免用户继续支付。
			// TODO 等待用户付款
			result.setServiceException(new ServiceException("pay_user_waiting"));
			return result;
		} else if ("20000".equals(response.getCode())) {
			// 未知异常 调用查询接口确认支付结果，详见异常处理。
			result.setFlag(false);
			result.setMsg(response.getSubCode() + " " + response.getSubMsg());
			return result;
		} else {
			result.setFlag(false);
		}

		return result;
	}

	@Override
	public ObjectResult<AlipayTradeQueryResponse> aliTradeQuery(String outTradeNo, String tradeNo) {
		ObjectResult<AlipayTradeQueryResponse> result = new ObjectResult<>();
		AlipayTradeQueryResponse response = AliPayManager.getInstance().tradeQuery(outTradeNo, tradeNo);

		boolean flag = false;
		if (response.isSuccess()) {// 调用成功
			// 交易当前状态
			if (WXPayConstants.TRADE_STATE_SUCCESS.equals(response.getTradeStatus())) {
				// 成功
			} else if (AliPayConstants.TRADE_STATE_WAIT_BUYER_PAY.equals(response.getTradeStatus())) {
				// 交易创建，等待买家付款
			} else if (AliPayConstants.TRADE_STATE_CLOSED.equals(response.getTradeStatus())) {
				// 未付款交易超时关闭，或支付完成后全额退款
			} else if (AliPayConstants.TRADE_STATE_FINISHED.equals(response.getTradeStatus())) {
				// 交易结束，不可退款
			}
		} else {
			// 调用失败
			response.getSubMsg();
			result.setMsg(response.getSubMsg());
		}

		result.setFlag(flag);
		result.setData(response);
		logger.debug("aliTradeCancel response:" + JSON.toJSONString(response));
		return result;
	}

	@Override
	public ObjectResult<AlipayTradeCancelResponse> aliTradeCancel(String outTradeNo, String tradeNo) {
		ObjectResult<AlipayTradeCancelResponse> result = new ObjectResult<>();
		AlipayTradeCancelResponse response = AliPayManager.getInstance().tradeCancel(outTradeNo, tradeNo);

		boolean flag = false;
		if (response.isSuccess()) { // 调用成功
			// 是否需要重试，Y/N
			if ("Y".equals(response.getRetryFlag())) {
				// 是

			} else if ("N".equals(response.getRetryFlag())) {

			}

			if ("close".equals(response.getAction())) {
				// 关闭交易，无退款

			} else if ("refund".equals(response.getAction())) {
				// 产生了退款
			}
		} else {
			// 调用失败
			response.getSubMsg();
			result.setMsg(response.getSubMsg());
		}
		result.setFlag(flag);
		result.setData(response);
		logger.debug("aliTradeCancel response:" + JSON.toJSONString(response));
		return result;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public String wechatPayCallback(String resStr) throws ServiceException {
		String result = WXPayManager.getInstance().return2WXFail("");
		WXPayCallbackRequest data = WXPayManager.getInstance().payCallback(resStr);
		if (data == null) {
			return result;
		}
		logger.info("wechatPay callback data=======>: " + JSON.toJSONString(data));

		String out_trade_no = data.getOut_trade_no(); // 商户订单号
		String transaction_id = data.getTransaction_id(); // 微信支付订单号
		int total_fee = data.getTotal_fee(); // 订单总金额，单位为分

		// 状态码
		if (!WXPayConstants.SUCCESS.equals(data.getReturn_code())) {
			return WXPayManager.getInstance().return2WXFail("状态码FAIL");
		}

		int orderState = 2;
		// 业务结果
		if (WXPayConstants.SUCCESS.equals(data.getResult_code())) {// 交易成功
			orderState = 1;
		} else if (WXPayConstants.FAIL.endsWith(data.getResult_code())) {// 交易失败
			orderState = 2;
		}

		if (StringUtil.isEmpty(out_trade_no)) {
			return WXPayManager.getInstance().return2WXFail(null);
		}

		try {
			// 有存在的处理
			String cacheOutTradeNo = payCacheImpl.getPayCallbackFlag(out_trade_no);
			if (!StringUtil.isEmpty(cacheOutTradeNo)) {
				return null;
			}
			// 设置标志
			payCacheImpl.setPayCallbackFlag(out_trade_no);

			// 处理支付成功业务
			OrderBean order = orderImpl.selectByOrderNo(out_trade_no);
			if (order == null) {
				return WXPayManager.getInstance().return2WXFail("订单不存在");
			}
			// 已经支付成功
			if (order.getStatus() != null && order.getStatus() == 1) {
				return WXPayManager.getInstance().return2WXSucess();
			}

			// 交易金额
			if (total_fee != (int) (order.getGetMoney() * 100)) {
				return WXPayManager.getInstance().return2WXFail("交易金额不正确");
			}

			// 更新订单状态
			updateOrderPaySuccess(order, transaction_id, orderState, JSON.toJSONString(data));
			result = WXPayManager.getInstance().return2WXSucess();
		} finally {
			// 清除标志
			payCacheImpl.clearPayCallbackFlag(out_trade_no);
		}
		return result;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public String aliPayCallback(Map<String, String> params) throws ServiceException, AlipayApiException {
		String result = AliPayManager.getInstance().getPayResponseFail();
		String app_id = params.get("app_id");
		String seller_email = params.get("seller_email");
		String trade_status = params.get("trade_status");
		String trade_no = params.get("trade_no"); // 支付宝交易号
		String out_trade_no = params.get("out_trade_no"); // 商家内部订单好
		String total_amount = params.get("total_amount"); // 本次交易支付的订单金额，单位为人民币（元）,精确小数点后两位

		// 交易状态校验
		if (!AliPayConstants.TRADE_STATE_WAIT_BUYER_PAY.equals(trade_status)
				&& !AliPayConstants.TRADE_STATE_CLOSED.equals(trade_status)
				&& !AliPayConstants.TRADE_STATE_SUCCESS.equals(trade_status)
				&& !AliPayConstants.TRADE_STATE_FINISHED.equals(trade_status)) {
			logger.info("aliPayCallback--------->1");
			return AliPayManager.getInstance().getPayResponseFail();
		}

		// 交易创建，等待买家付款
		if (AliPayConstants.TRADE_STATE_WAIT_BUYER_PAY.equals(trade_status)) {
			logger.info("aliPayCallback--------->WAIT_BUYER_PAY----->out_trade_no:" + out_trade_no);

		} else if (AliPayConstants.TRADE_STATE_CLOSED.equals(trade_status)) {
			// 未付款交易超时关闭，或支付完成后全额退款
			logger.info("aliPayCallback--------->TRADE_CLOSED----->out_trade_no:" + out_trade_no);

		} else if (AliPayConstants.TRADE_STATE_FINISHED.equals(trade_status)) {
			// 交易结束，不可退款
			logger.info("aliPayCallback--------->TRADE_FINISHED----->out_trade_no:" + out_trade_no);

		} else if (AliPayConstants.TRADE_STATE_SUCCESS.equals(trade_status)) {
			// 交易支付成功
			logger.info("aliPayCallback--------->TRADE_SUCCESS----->out_trade_no:" + out_trade_no);

			try {
				// 有存在的处理
				String cacheOutTradeNo = payCacheImpl.getPayCallbackFlag(out_trade_no);
				if (!StringUtil.isEmpty(cacheOutTradeNo)) {
					logger.info("aliPayCallback--------->TRADE_SUCCESS----->1");
					return AliPayManager.getInstance().getPayResponseFail();
				}
				payCacheImpl.setPayCallbackFlag(out_trade_no);

				// 1、验 seller_email
				if (StringUtil.isEmpty(seller_email)) {
					logger.info("aliPayCallback--------->TRADE_SUCCESS----->2");
					return AliPayManager.getInstance().getPayResponseFail();
				}

				// 2、验app_id
				if (StringUtil.isEmpty(app_id)) {
					logger.info("aliPayCallback--------->TRADE_SUCCESS----->3");
					return AliPayManager.getInstance().getPayResponseFail();
				}

				if (!app_id.equals(AliPayManager.getInstance().getAppId())) {
					logger.info("aliPayCallback--------->TRADE_SUCCESS----->4");
					return AliPayManager.getInstance().getPayResponseFail();
				}

				// 3、验out_trade_no
				OrderBean order = orderImpl.selectByOrderNo(out_trade_no);
				if (order == null) {
					logger.info("aliPayCallback--------->TRADE_SUCCESS----->5");
					return AliPayManager.getInstance().getPayResponseFail();
				}
				// 已经支付处理过
				if (order.getStatus() != null && order.getStatus() == 1) {
					logger.info("aliPayCallback--------->TRADE_SUCCESS----->6");
					return AliPayManager.getInstance().getPayResponseSucess();
				}

				// 4、验totalAmount
				if (StringUtil.isEmpty(total_amount)) {
					logger.info("aliPayCallback--------->TRADE_SUCCESS----->7");
					return AliPayManager.getInstance().getPayResponseFail();
				}

				// 保留小数点后两位
				double totalAmount = AlipayUtil.getDouble(order.getGetMoney());

				if (Double.valueOf(total_amount) != totalAmount) {
					logger.info("aliPayCallback--------->TRADE_SUCCESS----->8");
					return AliPayManager.getInstance().getPayResponseFail();
				}

				// 更新订单状态
				updateOrderPaySuccess(order, trade_no, 1, JSON.toJSONString(params));

				logger.info("aliPayCallback--------->TRADE_SUCCESS----->9");
				return AliPayManager.getInstance().getPayResponseSucess();
			} finally {
				payCacheImpl.clearPayCallbackFlag(out_trade_no);
			}

		}
		return result;
	}

	@Transactional
	@Override
	public ObjectResult<ROrderStatusBean> queryOrderStatus(String orderNo) {
		ObjectResult<ROrderStatusBean> result = new ObjectResult<>();
		// 查询订单信息
		OrderBean order = orderImpl.selectByOrderNo(orderNo);
		if (order == null) {
			throw new ServiceException("object_is_not_exist", "订单信息");
		}

		// 订单状态信息
		ROrderStatusBean resData = new ROrderStatusBean();
		resData.setOid(order.getOid());
		resData.setOrderNo(orderNo);
		resData.setStatus(order.getStatus());
		resData.setOrderType(order.getOrderType());
		resData.setCreateTime(order.getCreateTime() != null ? order.getCreateTime().getTime() / 1000 : 0);
		resData.setPayType(order.getPayType());
		resData.setPayTime(order.getPayTime() != null ? order.getPayTime().getTime() / 1000 : 0);
		resData.setCompleteTime(order.getCompleteTime() != null ? order.getCompleteTime().getTime() / 1000 : 0);
		result.setData(resData);

		// 已经支付处理过
		if (order.getStatus() != null && order.getStatus() == 1) {
			return result;
		}

		// 支付方式：1会员卡支付2现金3银联4支付宝5微信6信用卡7签单
		int payType = order.getPayType();

		if (payType == 4) {// 支付宝
			queryAliPayOrder(result, order, orderNo);
		} else if (payType == 5) {// 微信
			queryWXPayOrder(result, order, orderNo);
		}

		resData.setStatus(order.getStatus());
		return result;
	}

	// 查询支付宝支付的订单状态
	private void queryAliPayOrder(ObjectResult<ROrderStatusBean> result, OrderBean order, String orderNo) {
		AlipayTradeQueryResponse response = AliPayManager.getInstance().tradeQuery(orderNo, null);
		if (response == null) {
			throw new ServiceException("pay_query_error");
		}

		// 支付宝交易号
		String trade_no = response.getTradeNo();
		if (!response.isSuccess()) {// 调用失败
			response.getSubMsg();
			result.setMsg(response.getSubMsg());
			return;
		} else if (response.isSuccess()) { // 调用成功
			// 交易当前状态
			if (AliPayConstants.TRADE_STATE_SUCCESS.equals(response.getTradeStatus())) {
				// 成功
				// 更新订单状态
				updateOrderPaySuccess(order, trade_no, 1, JSON.toJSONString(response));
			} else if (AliPayConstants.TRADE_STATE_WAIT_BUYER_PAY.equals(response.getTradeStatus())) {
				// 交易创建，等待买家付款
				result.setFlag(false);
				result.setMsg("交易创建，等待买家付款 " + response.getSubCode() + " " + response.getSubMsg());
				return;
			} else if (AliPayConstants.TRADE_STATE_CLOSED.equals(response.getTradeStatus())) {
				// 未付款交易超时关闭，或支付完成后全额退款
				result.setFlag(false);
				result.setMsg("未付款交易超时关闭，或支付完成后全额退款 " + response.getSubCode() + " " + response.getSubMsg());
				return;
			} else if (AliPayConstants.TRADE_STATE_FINISHED.equals(response.getTradeStatus())) {
				// 交易结束，不可退款
				result.setFlag(false);
				result.setMsg("交易结束，不可退款 " + response.getSubCode() + " " + response.getSubMsg());
				return;
			}
		}
	}

	// 查询微信支付的订单状态
	private void queryWXPayOrder(ObjectResult<ROrderStatusBean> result, OrderBean order, String orderNo) {
		WXOrderqueryResponse response = WXPayManager.getInstance().orderquery(null, orderNo);
		if (response == null) {
			throw new ServiceException("pay_query_error");
		}

		// 状态码 不成功
		if (!WXPayConstants.SUCCESS.equals(response.getReturn_code())) {
			throw new ServiceException("pay_query_error");
		}

		// 业务结果 不成功
		if (!WXPayConstants.SUCCESS.equals(response.getResult_code())) {
			result.setFlag(false);
			result.setMsg(response.getErr_code() + " " + response.getErr_code_des());
			return;
		}

		// 微信支付订单号
		String transaction_id = response.getTransaction_id();

		// 交易状态 不成功
		if (!WXPayConstants.SUCCESS.equals(response.getTrade_state())) {
			if (WXPayConstants.TRADE_STATE_REFUND.equals(response.getTrade_state())) { // 转入退款
				result.setFlag(false);
				result.setMsg("转入退款" + response.getTrade_state_desc());
				return;
			} else if (WXPayConstants.TRADE_STATE_NOTPAY.equals(response.getTrade_state())) {// 未支付
				result.setFlag(false);
				result.setMsg("未支付" + response.getTrade_state_desc());
				return;
			} else if (WXPayConstants.TRADE_STATE_CLOSED.equals(response.getTrade_state())) {// 已关闭
				result.setFlag(false);
				result.setMsg("已关闭" + response.getTrade_state_desc());
				return;
			} else if (WXPayConstants.TRADE_STATE_REVOKED.equals(response.getTrade_state())) {// 已撤销（刷卡支付）
				result.setFlag(false);
				result.setMsg("已撤销（刷卡支付）" + response.getTrade_state_desc());
				return;
			} else if (WXPayConstants.TRADE_STATE_USERPAYING.equals(response.getTrade_state())) {// 用户支付中
				result.setServiceException(new ServiceException("pay_user_waiting"));
				return;
			} else if (WXPayConstants.TRADE_STATE_PAYERROR.equals(response.getTrade_state())) {// 支付失败(其他原因，如银行返回失败)
				result.setFlag(false);
				result.setMsg("支付失败(其他原因，如银行返回失败)" + response.getTrade_state_desc());
				return;
			}
		} else { // 支付成功
			updateOrderPaySuccess(order, transaction_id, 1, JSON.toJSONString(response));
		}
	}

	/**
	 * 订单支付完成，更新系统数据库中订单状态,然后在更新后续的状态
	 * 
	 * @param order
	 *            订单信息
	 * @param trade_no
	 *            订单号
	 * @param status
	 *            订单状态 状态：0未支付1已支付2支付失败3支付取消4支付超时
	 * @param payResponse
	 *            支付返回信息
	 */
	private void updateOrderPaySuccess(OrderBean order, String trade_no, int orderStatus, String payResponse) {
		// 更新订单状态
		boolean flag = orderImpl.updateStatusByOid(order.getOid(), trade_no, orderStatus, payResponse) > 0;
		if (!flag) {
			throw new ServiceException("database_update_fail", "订单");
		}
		// 订单状态更改 为 已支付
		order.setStatus(orderStatus);
		if (order.getOrderType() == null) {
			return;
		}

		// 支付不成功，不需要执行下面的代码
		if (orderStatus != 1) {
			return;
		}

		// 订单类型：1影厅开厅2续时消费3转厅4商品消费5会员卡充值
		if (order.getOrderType() == 4) {
			// 根据oid查询产品订单
			List<ProOrderBean> updateProOrderList = new ArrayList<>();
			List<ProOrderBean> proOrderList = proOrderImpl.selectListByOid(order.getOid());
			if (proOrderList != null) {
				List<ProStockBean> proStockList = new ArrayList<ProStockBean>();
				for (ProOrderBean pro : proOrderList) {
					ProOrderBean proOrder = new ProOrderBean();
					proOrder.setOid(pro.getOid());
					proOrder.setStatus(1);
					updateProOrderList.add(proOrder);

					ProStockBean stock = new ProStockBean();
					stock.setStoreHouseId(order.getStoreHouseId());
					stock.setProductId(pro.getProductId());
					stock.setStore(-Math.abs(pro.getNumber()));
					proStockList.add(stock);
				}

				// 更新产品订单中的支付状态
				flag = proOrderImpl.updateStatusBatch(updateProOrderList) > 0;
				if (!flag) {
					throw new ServiceException("database_update_fail", "订单商品");
				}
				// 更新库存
				flag = proStockImpl.updateBatch(proStockList) > 0;
				if (!flag) {
					throw new ServiceException("database_update_fail", "商品库存");
				}
			}
		}
	}
}
